import { ipcMain, app, shell, dialog, BrowserWindow } from 'electron';
import { WindowManager } from '../window';
import { sshService } from '../services/sshService';

export class IPCManager {
  private windowManager: WindowManager;

  constructor(windowManager: WindowManager) {
    this.windowManager = windowManager;
  }

  public initialize(): void {
    this.setupWindowHandlers();
    this.setupAppHandlers();
    this.setupMenuHandlers();
    this.setupThemeHandlers();
    this.setupConfigHandlers();
    this.setupNotificationHandlers();
    this.setupDialogHandlers();
    this.setupSSHHandlers();
  }

  private setupWindowHandlers(): void {
    // 窗口控制
    ipcMain.handle('window-minimize', () => {
      this.windowManager.minimizeMainWindow();
    });

    ipcMain.handle('window-maximize', () => {
      this.windowManager.maximizeMainWindow();
    });

    ipcMain.handle('window-close', () => {
      this.windowManager.closeMainWindow();
    });

    ipcMain.handle('window-is-maximized', () => {
      return this.windowManager.isMainWindowMaximized();
    });

    // 窗口状态
    ipcMain.handle('window-get-state', () => {
      const mainWindow = this.windowManager.getMainWindow();
      if (!mainWindow) return null;
      
      return {
        width: mainWindow.getBounds().width,
        height: mainWindow.getBounds().height,
        x: mainWindow.getBounds().x,
        y: mainWindow.getBounds().y,
        maximized: mainWindow.isMaximized(),
        minimized: mainWindow.isMinimized(),
      };
    });

    ipcMain.handle('window-set-state', (_, state) => {
      const mainWindow = this.windowManager.getMainWindow();
      if (!mainWindow) return;
      
      if (state.width && state.height) {
        mainWindow.setSize(state.width, state.height);
      }
      if (state.x !== undefined && state.y !== undefined) {
        mainWindow.setPosition(state.x, state.y);
      }
      if (state.maximized !== undefined) {
        if (state.maximized && !mainWindow.isMaximized()) {
          mainWindow.maximize();
        } else if (!state.maximized && mainWindow.isMaximized()) {
          mainWindow.unmaximize();
        }
      }
    });
  }

  private setupAppHandlers(): void {
    // 应用信息
    ipcMain.handle('app-get-version', () => {
      return app.getVersion();
    });

    ipcMain.handle('app-get-platform', () => {
      return process.platform;
    });

    ipcMain.handle('app-get-arch', () => {
      return process.arch;
    });

    // 应用控制
    ipcMain.handle('app-quit', () => {
      app.quit();
    });

    ipcMain.handle('app-relaunch', () => {
      app.relaunch();
      app.exit();
    });

    // 路径相关
    ipcMain.handle('app-get-path', (_, name: string) => {
      return app.getPath(name as any);
    });

    ipcMain.handle('app-show-item-in-folder', (_, fullPath: string) => {
      shell.showItemInFolder(fullPath);
    });
  }

  private setupMenuHandlers(): void {
    // 菜单控制
    ipcMain.handle('menu-set-menu', (_, template) => {
      // TODO: 设置菜单
    });

    ipcMain.handle('menu-popup', (_, template) => {
      // TODO: 显示弹出菜单
    });

    // 页面导航
    ipcMain.handle('nav-navigate', (_, path: string) => {
      const mainWindow = this.windowManager.getMainWindow();
      if (mainWindow) {
        mainWindow.webContents.send('navigate-to', path);
      }
    });

    ipcMain.handle('nav-get-current', () => {
      // TODO: 获取当前页面
      return '/';
    });
  }

  private setupThemeHandlers(): void {
    // 主题相关
    ipcMain.handle('theme-get-current', () => {
      // TODO: 获取当前主题
      return 'light';
    });

    ipcMain.handle('theme-set', (_, theme: string) => {
      // TODO: 设置主题
      const mainWindow = this.windowManager.getMainWindow();
      if (mainWindow) {
        mainWindow.webContents.send('theme-changed', theme);
      }
    });

    ipcMain.handle('theme-get-available', () => {
      // TODO: 获取可用主题列表
      return ['light', 'dark', 'auto'];
    });
  }

  private setupConfigHandlers(): void {
    // 配置相关
    ipcMain.handle('config-get', (_, key: string) => {
      // TODO: 获取配置
      return null;
    });

    ipcMain.handle('config-set', (_, key: string, value: any) => {
      // TODO: 设置配置
    });

    ipcMain.handle('config-delete', (_, key: string) => {
      // TODO: 删除配置
    });

    ipcMain.handle('config-get-all', () => {
      // TODO: 获取所有配置
      return {};
    });
  }

  private setupNotificationHandlers(): void {
    // 通知相关
    ipcMain.handle('notification-show', (_, options: any) => {
      // TODO: 显示通知
      const { Notification } = require('electron');
      if (Notification.isSupported()) {
        const notification = new Notification(options);
        notification.show();
      }
    });

    ipcMain.handle('notification-request-permission', () => {
      // TODO: 请求通知权限
      return true;
    });
  }

  private setupDialogHandlers(): void {
    // 对话框相关
    ipcMain.handle('dialog-show-open', async (_, options: any) => {
      const mainWindow = this.windowManager.getMainWindow();
      if (!mainWindow) return { canceled: true };
      
      return await dialog.showOpenDialog(mainWindow, options);
    });

    ipcMain.handle('dialog-show-save', async (_, options: any) => {
      const mainWindow = this.windowManager.getMainWindow();
      if (!mainWindow) return { canceled: true };
      
      return await dialog.showSaveDialog(mainWindow, options);
    });

    ipcMain.handle('dialog-show-message', async (_, options: any) => {
      const mainWindow = this.windowManager.getMainWindow();
      if (!mainWindow) return { response: 0 };
      
      return await dialog.showMessageBox(mainWindow, options);
    });

    ipcMain.handle('dialog-show-error', async (_, options: any) => {
      const mainWindow = this.windowManager.getMainWindow();
      if (!mainWindow) return { response: 0 };

      return await dialog.showErrorBox(options.title, options.content);
    });
  }

  private setupSSHHandlers(): void {
    // SSH连接相关
    ipcMain.handle('ssh-connect', async (_, connection, auth) => {
      try {
        const result = await sshService.connect(
          connection,
          auth,
          (data: string) => {
            // 发送数据到渲染进程
            const mainWindow = this.windowManager.getMainWindow();
            if (mainWindow) {
              mainWindow.webContents.send('ssh-data', connection.id, data);
            }
          },
          (error: Error) => {
            // 发送错误到渲染进程
            const mainWindow = this.windowManager.getMainWindow();
            if (mainWindow) {
              mainWindow.webContents.send('ssh-error', connection.id, error.message);
            }
          }
        );
        return { success: true, connectionId: result.id };
      } catch (error: any) {
        return { success: false, error: error.message };
      }
    });

    ipcMain.handle('ssh-disconnect', (_, connectionId: string) => {
      sshService.disconnect(connectionId);
      return { success: true };
    });

    ipcMain.handle('ssh-send-data', (_, connectionId: string, data: string) => {
      const success = sshService.sendData(connectionId, data);
      return { success };
    });

    ipcMain.handle('ssh-resize', (_, connectionId: string, cols: number, rows: number) => {
      const success = sshService.resize(connectionId, cols, rows);
      return { success };
    });

    ipcMain.handle('ssh-is-connected', (_, connectionId: string) => {
      const connected = sshService.isConnected(connectionId);
      return { connected };
    });

    // 断开所有连接
    ipcMain.handle('ssh-disconnect-all', () => {
      sshService.disconnectAll();
      return { success: true };
    });
  }
}